/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.chanceit.ssss.fragments;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.gl.customview.PullToRefreshView;
import org.gl.customview.PullToRefreshView.OnFooterRefreshListener;
import org.gl.customview.PullToRefreshView.OnHeaderRefreshListener;
import org.gl.ui.manger.AjaxCallBackProxy;
import org.gl.utils.lg;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.chanceit.ssss.activity.R;
import com.chanceit.ssss.adapters.BusinessTabPagerAdapter;
import com.chanceit.ssss.common.IntentExtraDataKeyValue;
import com.chanceit.ssss.data.DataSources;
import com.chanceit.ssss.data.ExceptionCodeParsh;

/**
 * the all Complaint list from this carer 
 * 
 * @author Administrator
 * 
 */
//{"company":"东风本田汽车惠盛特约销售服务店","tel":"18688959588","carName":"明锐16","userName":"张维军","para":[{"createTime":"2013-10-16 09:00:41","parasValue":"12,967,10000,20,36,14,0,37,0,18,65496,0,6,0","paraCode":"00000100000000000000000000000000"},{"createTime":"2013-10-15 18:59:45","parasValue":"15,1202,10000,19,36,14,0,36,0,18,65496,0,6,0","paraCode":"00000100000000000000000000000000"},{"createTime":"2013-10-15 09:33:11","parasValue":"13,1798,10000,21,54,17,0,62,0,19,65496,0,6,0","paraCode":"00000100000000000000000000000000"},{"createTime":"2013-10-14 17:42:30","parasValue":"47,1383,10000,63,28,14,0,28,0,40,65496,0,6,0","paraCode":"00000100000000000000000000000000"},{"createTime":"2013-10-14 17:26:12","parasValue":"0,0,10000,61,0,15,0,100,0,43,65496,0,6,0","paraCode":"00000100000000000000000000000000"},{"createTime":"2013-10-14 12:55:55","parasValue":"10,1326,10000,80,45,16,0,45,0,53,65496,0,6,0","paraCode":"00000100000000000000000000000000"},{"createTime":"2013-10-14 10:58:51","parasValue":"21,1074,10000,84,25,13,0,25,0,51,65496,0,6,0","paraCode":"00000100000000000000000000000000"},{"createTime":"2013-10-06 09:32:02","parasValue":"0,813,10000,25,58,14,0,59,0,24,65496,0,6,0","paraCode":"00000100000000000000000000000000"},{"createTime":"2013-10-05 13:19:14","parasValue":"13,1237,10000,48,59,15,0,52,0,41,65496,0,6,0","paraCode":"00000100000000000000000000000000"},{"createTime":"2013-10-05 11:13:12","parasValue":"1,811,10000,52,44,13,0,44,0,34,65496,0,6,0","paraCode":"00000100000000000000000000000000"},{"createTime":"2013-10-05 10:52:58","parasValue":"2,810,10000,54,45,14,0,45,0,27,65496,0,6,0","paraCode":"00000100000000000000000000000000"}]}
public class CarExceptionHistoryListFragment extends BaseFragment implements
		OnItemClickListener, OnHeaderRefreshListener, OnFooterRefreshListener {
	OnListFragmentSelectedListener mCallback;
	DataSources ds;
	List<Map<String, Object>> contents = new ArrayList<Map<String, Object>>();
	String[] keys = new String[] { "userName", "createTime", "carName",
			"paraCode", "titleIconIndex" ,"warnId"};
	private final String[] exception = new String[] { "当前车速", "发送机转速", "电瓶电压",
			"冷却液温度", "发动机负载", "节气门位置", "大气压", "进气歧管绝对压力", "空气流量", "环境空气温度",
			"进气温度", "OBD协议", "OBD标准", "燃油量", "未知异常", "未知异常" };
	//
	ListView listView;
	JSONObject selectCarerInfo;
	protected JSONArray userListJosnAry = new JSONArray();
	private String userId;
	private int titleIconIndex;
	public interface OnListFragmentSelectedListener {
		/** Called by HeadlinesFragment when a list item is selected */
		public void onArticleSelected(int position);
	}

	public View view;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.exception_carer_history_list, container, false);
		ds = new DataSources();
		listView = (ListView) view.findViewById(R.id.order_carer_lv);
		listView.setOnItemClickListener(this);
		mPullToRefreshView = (PullToRefreshView) (view
				.findViewById(R.id.main_pull_refresh_view));
		mPullToRefreshView.setOnHeaderRefreshListener(this);
		mPullToRefreshView.setOnFooterRefreshListener(this);
		userId = IntentExtraDataKeyValue.getUserInfoToIntent().optString("userId");
		initData(null);
		TextView tv = (TextView) view.findViewById(R.id.tv_title_tv_content);
		tv.setText("异常参数详情");
		return view;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	final int page = 1;
	PullToRefreshView mPullToRefreshView;
	SimpleAdapter adapter;

	@Override
	public void onFooterRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {

			@Override
			public void run() {
//				page++;
				getData(page, userId);
				mPullToRefreshView.onFooterRefreshComplete();
			}
		}, 1000);
	}

	@Override
	public void onHeaderRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {

			@Override
			public void run() {
//				page = 1;
				getData(null, userId);
				mPullToRefreshView.onHeaderRefreshComplete();
			}
		}, 1000);

	}

	protected void initData(Integer _page) {
		if (adapter != null && userListJosnAry != null
				&& userListJosnAry.length() > 0) {
			setListAdapter(adapter);
			lg.i(TAG, "resotre the fragment");
			return;
		}
		getData(null, userId);

	}

	protected void getData(Integer _page, String userId) {
		ds.getCarExceptionHistoryList(_page,userId,
				new AjaxCallBackProxy<String>(view.findViewById(R.id.loading)) {
					public void onLoading(long count, long current) {
					}

					@Override
					public void onFailure(Throwable t, int errorNo,
							String strMsg) {
						super.onFailure(t, errorNo, strMsg);
					}

					@SuppressWarnings("unused")
					public void onSuccess(String t) {
						lg.i(TAG, t);
						if (getActivity()==null) {
							loadFailed("getActivity() is null");
						}
						int code = 0;
						String mesage = "";
						try {
							JSONObject result = new JSONObject(t);
							;
							code = result.optInt(webkey.code);
							mesage = result.optString(webkey.reason);

//							JSONArray newJsonArray = result
//									.optJSONArray(webkey.result);
							JSONArray newJsonArray = result
									.optJSONArray("para");
							contents.removeAll(contents);
							if (page <= 1) {// 如果当前页码为<=1 说明是第一次加载 清楚以前的旧数据
								userListJosnAry = null;
								userListJosnAry = newJsonArray;
							} else {// 否则就是加载更多的分页数据,把新的数据添加到集合中
								for (int i = 0; i < newJsonArray.length(); i++) {
									userListJosnAry.put(newJsonArray.opt(i));
								}
							}
							if (userListJosnAry == null) {
								userListJosnAry = new JSONArray();
							}
							int count = userListJosnAry.length();
							for (int i = 0; i < count; i++) {
								Map<String, Object> map = new HashMap<String, Object>();
								JSONObject temp = userListJosnAry
										.getJSONObject(i);
								for (String key : keys) {
									Object o = temp.opt(key);
									if (o == null
											|| o.toString().equals("null")) {
										o = "";
									}
									if (!TextUtils.isEmpty(o.toString())
											&& "paraCode".equals(key)) {
										o = parshExcepiton(o,temp.optString("parasValue"));
									}
									if ("titleIconIndex".equals(key)) {
										o = BusinessTabPagerAdapter.icons[titleIconIndex];
									}
									map.put(key, o.toString());
								}
								contents.add(map);
							}
							if (adapter == null) {
								if (contents.size() > 0) {
									adapter = new SimpleAdapter(
											context,
											(List<Map<String, Object>>) contents,
											R.layout.list_item_order_carer,
											keys, new int[] { R.id.textView1,
													R.id.textView2,
													R.id.textView3,
													R.id.textView4,
													R.id.imageView1 });
									setListAdapter(adapter);
								}
							} else {
								adapter.notifyDataSetChanged();
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
//							page--;
							if (code != 0) {
								loadFailed(mesage);
							} else {
								loadSuccessed();
//								page++;
							}
						}

					}
				});
	}

	protected void setListAdapter(SimpleAdapter adapter) {
		listView.setAdapter(adapter);

	}

	@Override
	public void onStart() {
		super.onStart();
		// if (getFragmentManager().findFragmentById(R.id.article_fragment) !=
		// null) {
		listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		// }
	}


	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		// Set the item as checked to be highlighted when in two-pane layout
		listView.setItemChecked(position, true);
		listView.setSelection(position);
	}

	@Override
	public void receiveMessage(Object message) {
		super.receiveMessage(message);
		getData(null, userId);
	}

	/**
	 * 获取异常的白话文标题
	 * 
	 * @param o
	 * @return
	 */
	private String parshExcepiton(Object o,String value) {
		return ExceptionCodeParsh.parshExcepiton(o, value);
	}
}